package com.xhorse.lockplatform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xhorse.lockplatform.comm.constant.FilePathDefine;
import com.xhorse.lockplatform.comm.util.FileTransport;
import com.xhorse.lockplatform.comm.util.GsonTransferUtil;
import com.xhorse.lockplatform.dao.mapper.XhBrandMapper;
import com.xhorse.lockplatform.dao.mapper.XhChipMapper;
import com.xhorse.lockplatform.model.XhChip;
import com.xhorse.lockplatform.service.ChipDataImportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChipDataImportServiceImpl implements ChipDataImportService {

    @Autowired
    private XhChipMapper xhChipMapper;

    @Override
    public void ChipDataImport(int regionId) {
        XhChipImport(regionId); // 2.导入XhLanguagePack数据
        FileTransport fileTransport = new FileTransport();
        fileTransport.deleteFile(FilePathDefine.CHIP_DATABASE + "jsonFile");
    }

    @Override
    public int findMaxVersion(String dbversion, int languageId) {
        return xhChipMapper.findMaxVersion(dbversion, languageId);
    }

    /**
     * xh_chip数据导入
     */
    public void XhChipImport(int regionId) {
        String filepath = FilePathDefine.CHIP_DATABASE + "chip_" + regionId
                + ".json";
        String JsonString = GsonTransferUtil.JsonfileToString(filepath).trim();
        JSONObject object = JSONObject.parseObject(JsonString);
        List<XhChip> chipList = JSONObject.parseArray(object.getString("list"), XhChip.class);
        int version = xhChipMapper.findMaxVersion("0", 1); // 获取当前数据库最大版本号,注：以中文作为基准选取版本号
        for (XhChip xhChip : chipList) {
            XhChip temp = xhChipMapper.selectChipInfo(xhChip);
            xhChip.setVersion(version + 1 + "");
            if (temp == null) {
                // 若是新增数据，则版本号+1
                xhChipMapper.insertSelective(xhChip);
            } else {
                if (!temp.equals(xhChip)) {
                    // 若是新增数据，则版本号+1
                    xhChipMapper.updateSelective(xhChip);
                }
            }
        }
    }

}
